package com.thb.pay.core.utils;

import com.google.common.collect.Lists;
import com.xiaoleilu.hutool.collection.CollUtil;
import lombok.Data;

import java.util.List;

public class MenuBuilder {

    List<Node> nodes = Lists.newArrayList();

    public MenuBuilder(List<Node> nodes) {
        super();
        this.nodes = nodes;
    }
    /**
     * 构建树形结构
     *
     * @return
     */
    public List<Node> buildTree() {
        List<Node> treeNodes = Lists.newArrayList();
        List<Node> rootNodes = getRootNodes();
        if (CollUtil.isNotEmpty(rootNodes)) {
            rootNodes.forEach(rootNode -> {
                buildChildNodes(rootNode);
                treeNodes.add(rootNode);
            });
        }
        return treeNodes;
    }

    /**
     * 递归子节点
     *
     * @param node
     */
    public void buildChildNodes(Node node) {
        List<Node> childrenList = getChildNodes(node);
        if (CollUtil.isNotEmpty(childrenList)) {
            childrenList.forEach(childNode -> {
                buildChildNodes(childNode);
            });
            node.setList(childrenList);
        }
    }

    /**
     * 获取父节点下所有的子节点
     *
     * @param parentNode
     * @return
     */
    public List<Node> getChildNodes(Node parentNode) {
        List<Node> childNodes = Lists.newArrayList();
        nodes.forEach(node -> {
            if (parentNode.getResourceId().equals(node.getParentId())) {
                childNodes.add(node);
            }
        });
        return childNodes;
    }

    /**
     * 判断是否为根节点
     *
     * @param node
     * @return
     */
    public boolean rootNode(Node node) {
        boolean isRootNode = true;
        for (Node n : nodes) {
            if (node.getParentId() != null && node.getParentId().equals(n.getResourceId())) {
                isRootNode = false;
                break;
            }
        }
        return isRootNode;
    }

    /**
     * 获取集合中所有的根节点
     *
     * @return
     */
    public List<Node> getRootNodes() {
        List<Node> rootNodes = Lists.newArrayList();
        nodes.forEach(node -> {
            if (rootNode(node)) {
                rootNodes.add(node);
            }
        });
        return rootNodes;
    }

    @Data
    public static class Node {
        private Long resourceId;
        private String name;
        private String title;
        private String jump;
        private String icon;
        private Long parentId;
        private List<Node> list;

    }
}